<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter.native="handleQuery"/>
            </el-form-item>
            <el-form-item label="排站规则" prop="allotPlaceRule">
                <el-select v-model="queryParams.allotPlaceRule" placeholder="请选择排站规则" clearable>
                    <el-option v-for="dict in dict.type.score_ex_model_allot_place_rule_dict" :key="dict.value" :value="dict.value" :label="dict.label"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['score:ex_model:add']">新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['score:ex_model:edit']">修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['score:ex_model:remove']">删除
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="ex_modelList" @selection-change="handleSelectionChange" :height="table_height">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="名称" align="center" prop="name"/>
            <el-table-column label="最大学生数" align="center" prop="maxStudent"/>
            <el-table-column label="现场考官权重(%)" align="center" prop="sceneExaminerWi"/>
            <el-table-column label="中控考官权重(%)" align="center" prop="centerExaminerWi"/>
            <el-table-column label="远程考官权重(%)" align="center" prop="sshExaminerWi"/>
            <el-table-column label="考试间隔时间(分)" align="center" prop="examIntervalTime"/>
            <el-table-column label="考场数量" align="center" prop="scoreExModelPlaceCount"/>
            <el-table-column label="排站规则" align="center" prop="allotPlaceRule">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.score_ex_model_allot_place_rule_dict" :value="scope.row.allotPlaceRule"/>
                </template>
            </el-table-column>
            <el-table-column label="必过技能" align="center" prop="mustSkillList" :formatter="skillFormat"/>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['score:ex_model:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['score:ex_model:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList"/>

        <!-- 添加或修改考试模版表对话框 -->
        <el-drawer :title="title" :visible.sync="open" size="70%" append-to-body :destroy-on-close="true">
            <el-form ref="form" :model="form" :rules="rules" label-width="130px" size="mini">
                <el-row :gutter="11" style="margin-left: 20px">
                    <el-col :span="6" style="margin-top: 50px">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入名称" style="width: 160px;" clearable/>
                        </el-form-item>
                        <el-form-item label="最大学生数" prop="maxStudent">
                            <el-input-number :min="1" v-model="form.maxStudent" placeholder="请输入最大学生数" style="width: 160px;"/>
                        </el-form-item>
                        <el-form-item label="考试间隔时间(分)" prop="examIntervalTime">
                            <el-input-number :min="1" v-model="form.examIntervalTime" placeholder="请输入考试间隔时间(分)" style="width: 160px;"/>
                        </el-form-item>
                        <el-form-item label="排站规则" prop="allotPlaceRule">
                            <el-select v-model="form.allotPlaceRule" placeholder="请选择排站规则" style="width: 160px;" clearable>
                                <el-option v-for="dict in dict.type.score_ex_model_allot_place_rule_dict" :key="dict.value" :value="dict.value" :label="dict.label"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="必过技能" prop="mustSkill">
                            <el-select v-model="form.mustSkill" placeholder="请选择必过技能(多选,可自定义)" clearable multiple filterable allow-create default-first-option style="width: 470px">
                                <el-option v-for="dict in dict.type.score_ex_model_must_skill_dict" :key="dict.label" :label="dict.label" :value="dict.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6" style="margin-top: 50px">
                        <el-form-item label="现场考官权重(%)" prop="sceneExaminerWi">
                            <el-input-number :min="0" v-model="form.sceneExaminerWi" placeholder="请输入现场考官权重(%)" style="width: 160px;"/>
                        </el-form-item>
                        <el-form-item label="中控考官权重(%)" prop="centerExaminerWi">
                            <el-input-number :min="0" v-model="form.centerExaminerWi" placeholder="请输入现场考官权重(%)" style="width: 160px;"/>
                        </el-form-item>
                        <el-form-item label="远程考官权重(%)" prop="sshExaminerWi">
                            <el-input-number :min="0" v-model="form.sshExaminerWi" placeholder="请输入远程考官权重(%)" style="width: 160px;"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="11">
                        <div style="margin-bottom: 10px;float: right">
                            <el-button type="success" @click="submitForm" plain round>保 存</el-button>
                        </div>
                        <el-table :data="scoreExModelTimeList" size="mini"
                                  ref="scoreExModelTime" height="300">
                            <el-table-column align="center" label="考试时间分段">
                                <template slot="header" slot-scope="scope">
                                    <span>考试时间分段</span>
                                    <el-button type="primary" icon="el-icon-plus" size="mini" style="float: right" @click="handleAddScoreExModelTime" plain>添加一行</el-button>
                                </template>
                                <el-table-column label="名称" prop="name" align="center" width="150">
                                    <template slot-scope="scope">
                                        <el-input v-model="scope.row.name" size="mini" placeholder="请输入名称" clearable/>
                                    </template>
                                </el-table-column>
                                <el-table-column label="时间范围" align="center" prop="startTime">
                                    <template slot-scope="scope">
                                        <el-time-picker is-range size="mini" v-model="scope.row.timeRange" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" value-format="HH:mm:ss"></el-time-picker>
                                    </template>
                                </el-table-column>
                                <el-table-column width="37">
                                    <template slot="header" slot-scope="scope">
                                        <i class="el-icon-delete"/>
                                    </template>
                                    <template slot-scope="scope">
                                        <el-button type="text" icon="el-icon-circle-close" style="margin: 0;padding: 0" @click="handleDeleteScoreExModelTime(scope.$index)"/>
                                    </template>
                                </el-table-column>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row>
                    <el-divider><i class="el-icon-s-home"/>考场</el-divider>
                    <div class="place_big_box">
                        <el-button type="primary" icon="el-icon-plus" @click="handleAddScoreExModelPlace" style="position:fixed;right: 100px" plain>添加考场</el-button>
                        <div>
                            <EX_MODEL_PLACE style="float: left;" v-for="(place,index) in scoreExModelPlaceList" :deptOptions="deptOptions" :index="index" :place="place" @handleDeleteScoreExModelPlace="handleDeleteScoreExModelPlace"/>
                        </div>
                    </div>
                </el-row>
            </el-form>
        </el-drawer>
    </div>
</template>

<script>
import {listEx_model, getEx_model, delEx_model, addEx_model, updateEx_model} from "@/api/score/ex_model";
import EX_MODEL_PLACE from "./place/index.vue"
import {isEmptyArr, parseArr} from "@/utils/zzDouUtils/arrayUtil";
import {deptTreeSelect} from "@/api/system/user";
import {isEmptyStr, isNotNull, isNull} from "@/utils/zzDouUtils/objUtil";
import {before, nowDateStr} from "@/utils/zzDouUtils/dateUtil";

export default {
    name: "Ex_model",
    dicts: ['score_ex_model_must_skill_dict', 'score_ex_model_allot_place_rule_dict'],
    components: {EX_MODEL_PLACE},
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 考试模版表表格数据
            ex_modelList: [],
            // 考试模版时间分段表表格数据
            scoreExModelTimeList: [],
            //考试模板场地表格数据
            scoreExModelPlaceList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                name: null,
                allotPlaceRule: null,
            },
            // 科室树选项
            deptOptions: null,
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                name: [
                    {required: true, message: "请输入模版名称", trigger: "blur"}
                ],
                maxStudent: [
                    {required: true, message: "请输入最大学生数", trigger: "blur"}
                ],
                sceneExaminerWi: [
                    {required: true, message: "请输入现场考官权重(%)", trigger: "blur"}
                ],
                centerExaminerWi: [
                    {required: true, message: "请输入中控考官权重(%)", trigger: "blur"}
                ],
                sshExaminerWi: [
                    {required: true, message: "请输入远程考官权重(%)", trigger: "blur"}
                ],
                examIntervalTime: [
                    {required: true, message: "请输入考试间隔时间(分)", trigger: "blur"}
                ],
                allotPlaceRule: [
                    {required: true, message: "请选择排站规则", trigger: "blur"},
                ],
            }
        };
    },
    created() {
        this.getList();
    },
    methods: {
        parseArr,
        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        /** 查询考试模版表列表 */
        getList() {
            this.loading = true;
            listEx_model(this.queryParams).then(response => {
                this.ex_modelList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                name: null,
                maxStudent: null,
                sceneExaminerWi: null,
                centerExaminerWi: null,
                sshExaminerWi: null,
                examIntervalTime: null,
                allotPlaceRule: null,
                mustSkill: null,
            };
            this.scoreExModelTimeList = [];
            this.scoreExModelPlaceList = [];
            this.getDeptTree();
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.id)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加考试模版表";
            this.handleAddScoreExModelTime();
            this.handleAddScoreExModelPlace();
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getEx_model(id).then(response => {
                this.form = response.data;
                this.form.mustSkill = response.data.mustSkillList;
                this.scoreExModelTimeList = this.parseSearchRangeTime(response.data.scoreExModelTimeList);
                this.scoreExModelPlaceList = response.data.scoreExModelPlaceList;
                this.open = true;
                this.title = "修改考试模版表";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    //检查三个权重
                    let message = this.checkExaminerWi();
                    if (isNotNull(message)) { this.$modal.msgError(message); return; }
                    //检查时间分段
                    message = this.checkTimeListHasNull();
                    if (isNotNull(message)) { this.$modal.msgError(message); return; }
                    //检查场地列表
                    message = this.checkPlaceListHasNull();
                    if (isNotNull(message)) { this.$modal.msgError(message); return; }
                    this.form.scoreExModelTimeList = this.parseAddRangeTime(this.scoreExModelTimeList);
                    this.form.scoreExModelPlaceList = this.scoreExModelPlaceList;
                    if (this.form.id != null) {
                        updateEx_model(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addEx_model(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除考试模版表编号为"' + ids + '"的数据项？').then(function () {
                return delEx_model(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 考试模版时间分段表添加按钮操作 */
        handleAddScoreExModelTime() {
            const now = "00:00:00";
            this.scoreExModelTimeList.push({name: '', timeRange: [now, now]});
        },
        /** 考试模版时间分段表删除按钮操作 */
        handleDeleteScoreExModelTime(index) {
            if (index === 0) {return;}
            this.$delete(this.scoreExModelTimeList, index)
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('score/ex_model/export', {
                ...this.queryParams
            }, `ex_model_${nowDateStr()}.xlsx`)
        },
        /** 添加一行考场 */
        handleAddScoreExModelPlace() {
            this.scoreExModelPlaceList.push({deptId: null, skillId: null});
        },
        /** 删除一行 */
        handleDeleteScoreExModelPlace(index) {
            if (this.scoreExModelPlaceList.length <=1 ) {return;}
            this.$delete(this.scoreExModelPlaceList, index);
        },
        //----------------------------------
        //必过技能格式化
        skillFormat(row, column, cellValue) {
            let str = '';
            for (let i = 0; i < cellValue.length; i++) {
                str += cellValue[i];
                if (i != cellValue.length - 1) {
                    str += '、';
                }
            }
            return str;
        },
        //格式化时间范围
        parseAddRangeTime(timeArr) {
            let newArr = [];
            timeArr.forEach(item => {
                newArr.push({name: item.name, startTime: item.timeRange[0], endTime: item.timeRange[1]})
            })
            return newArr;
        },
        parseSearchRangeTime(timeArr) {
            let newArr = [];
            timeArr.forEach(item => {
                newArr.push({name: item.name, timeRange: [item.startTime, item.endTime]})
            })
            return newArr;
        },
        //---------------------------------------
        /** 检查三个权重 */
        checkExaminerWi(){
            const wi = parseInt(this.form.sceneExaminerWi) + parseInt(this.form.centerExaminerWi) + parseInt(this.form.sshExaminerWi);
            if (wi > 100 || wi < 90){
                return '权重占比总和不可大于100或者小于90';
            }
        },
        /** 检查时间分段 */
        checkTimeListHasNull(){
            for (let i = 0; i < this.scoreExModelTimeList.length; i++) {
                const time = this.scoreExModelTimeList[i];
                if (isEmptyStr(time.name)){
                    return `时间分段第${(i+1)}行名称为空`;
                }
                if (isEmptyArr(time.timeRange)){
                    return `时间分段第${(i+1)}行时间范围为空`;
                }
                if (i!==0 && before(time.timeRange[0],this.scoreExModelTimeList[i-1].timeRange[1])){//校验时间合法性
                    return `时间分段第${(i+1)}行开始时间不能在第${(i)}行结束时间之前`;
                }
            }
            return null;
        },
        /** 检查场地列表是否有空值 */
        checkPlaceListHasNull(){
            for (let i = 0; i < this.scoreExModelPlaceList.length; i++) {
                if (isNull(this.scoreExModelPlaceList[i].deptId)){
                    return `考场${(i+1)}科室未选择`;
                }
                if (isNull(this.scoreExModelPlaceList[i].skillId)){
                    return `考场${(i+1)}技能未选择`;
                }
            }
            return null;
        }
    }
};
</script>
<style>
.place_big_box { /* 最大盒子 */
    width: 100%;
    height: 600px;
    overflow: auto;
    padding-left: 30px;
    padding-top: 10px;
}
</style>

